package middleware

import (
	"encoding/json"
	"git.oschina.net/fanbuchi/redpack/conf/rsa"
	"git.oschina.net/fanbuchi/redpack/constant"
	"git.oschina.net/fanbuchi/redpack/domain"
	"git.oschina.net/fanbuchi/redpack/service"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)
//basic auth
func AuthRequired() gin.HandlerFunc {
	return func(context *gin.Context) {

	}
}

/*func SendResponse(c *gin.Context, err error, data interface{}) {
	code, message := errno.DecodeErr(err)

	// always return http.StatusOK
	c.JSON(http.StatusOK, Response{
		Code:    code,
		Message: message,
		CurrentTime: time.Now().Unix(),
		Data:    data,
	})
}

func DecodeErr(err error) (int, string) {
	if err == nil {
		return OK.Code, OK.Message
	}
	switch typed := err.(type) {
	case *Err:
		return typed.Code, typed.Message
	case *Errno:
		return typed.Code, typed.Message
	default:
	}

	return InternalServerError.Code, err.Error()
}*/


//oauth2 token
//验证算法 1.远程公钥加密，服务端私钥解密，判断是否在黑名单中，如果是就立即返回
func Oauth2AuthRequired() gin.HandlerFunc {
	return func(context *gin.Context) {
		substr:=" "
		authorization:= context.GetHeader("Authorization")
		if len(authorization)==0|| !strings.Contains(authorization,substr){
			context.AbortWithStatusJSON(http.StatusOK,domain.Rsp{Status:http.StatusUnauthorized,Msg:"Authorization is required!"})
			return
		}
		auth:=strings.Split(authorization,substr)
		if auth[0]=="" || auth[0]!="Bearer" || auth[1]==""{
			context.AbortWithStatusJSON(http.StatusOK,domain.Rsp{Status:http.StatusUnauthorized,Msg:"Bearer is required!"})
			return
		}
		token:=auth[1]

		oauthService:=new(service.OauthService)
		data,err:=rsa.RsaDecryptBase64(token)
		if err!=nil  {
			context.AbortWithStatusJSON(http.StatusOK,domain.Rsp{Status:http.StatusForbidden,Msg:err.Error()})
			return
		}
		var _oauth domain.Oauth
		json.Unmarshal(data,&_oauth)
		if _oauth.AccountId<=0 {//增加其他条件，规避token错误使用
			oauthResult,err:=oauthService.Revoke(token)
			if err!=nil  {
				context.AbortWithStatusJSON(http.StatusOK,domain.Rsp{Status:http.StatusForbidden,Msg:err.Error()})
				return
			}
			if &oauthResult==nil {
				context.AbortWithStatusJSON(http.StatusOK,domain.Rsp{Status:http.StatusUnauthorized,Msg:"401"})
				return
			}
			_oauth.AccountId=oauthResult.AccountId
			_oauth.Scope=oauthResult.Scope
		}

		context.Set(constant.AccountId,_oauth.AccountId)
		context.Set(constant.AccountRole,_oauth.Scope)
		context.Next()
		//context.Request.BasicAuth()
		//rsp:=context.Request.Response
	}
}